import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/setting.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/models/notification_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_list.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/custom_refresh_header.dart';
import 'package:go_router/go_router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SystemMessageListPage extends StatefulWidget {
  const SystemMessageListPage({super.key});

  @override
  State<SystemMessageListPage> createState() => _SystemMessageListPageState();
}

class _SystemMessageListPageState extends State<SystemMessageListPage> {
  final RefreshController _refreshController = RefreshController();
  List<NotificationItemModel> dataList = [];
  int page = 1;
  int size = 10;
  int totalPage = 1;
  bool loading = false;

  @override
  void initState() {
    super.initState();
    getDataList();
  }

  ///获取系统通知消息列表
  Future getDataList() async {
    try {
      setState(() {
        loading = true;
      });
      final result = await SettingAPI.getSettingMsgList(context, CommonPage(page: page, size: size));
      page = result?.page ?? 1;
      size = result?.size ?? 10;
      totalPage = result?.totalPage ?? 1;
      List<NotificationItemModel> currList;
      if (page == 1) {
        currList = result?.list ?? [];
      } else {
        currList = [...dataList, ...result?.list??[]];
      }
      if (page == totalPage) {
        _refreshController.loadNoData();
      }
      setState(() {
        dataList = currList;
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  Future<void> _loadMore() async {
    if (page < totalPage) {
      page++;
      await getDataList();
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: Column(
        children: [
          const CommonTitleWidget(txt: '系统消息'),
          Expanded(child: Container(
            margin: EdgeInsets.only(top: 20.w, left: Constant.PAGEPADDING.w, right: Constant.PAGEPADDING.w, bottom: 80.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: dataList.isNotEmpty ? CommonListWidget(
              controller: _refreshController,
              enablePullDown: false,
              enablePullUp: true,
              onLoading: _loadMore,
              header: CustomFreshHeader(refreshController: _refreshController),
              child: ListView.builder(
                physics: const ClampingScrollPhysics(),
                itemCount: dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  final item = dataList[index];
                  return GestureDetector(
                    onTap: () {
                      context.push('/system_message_detail', extra: {
                        'id': item.id
                      });
                    },
                    child: Container(
                      key: ValueKey(item.id),
                      height: 110.w,
                      padding: EdgeInsets.only(bottom: 10.w),
                      margin: EdgeInsets.symmetric(horizontal: 35.w),
                      decoration: BoxDecoration(
                        border:  Border(
                          bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor)
                        )
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.end,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Image.asset('assets/icons/icon_notification.png', height: 30.w),
                              SizedBox(width: 6.w,),
                              Expanded(child: CommonText(txt: item.title??'')),
                              CommonText(txt: item.createdAt?.split(' ')[0]??'-', fontSize: 26.sp),
                            ],
                          ),
                          SizedBox(height: 5.w),
                          Text(item.content??'-', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 26.sp, color: ColorStyle.textColor),)
                        ],
                      ),
                    ),
                  );
                },
              ),
            ) : const Center(child: CommonText(txt: '暂无数据')),
          ))
        ],
      ),
    );
  }
}
